//
//  MyOrdersController.swift
//  Fancyswap
//
//  Created by Cheikh Bara on 2015-03-23.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import UIKit
// import Alamofire


class MyOrdersController: UICollectionViewController {
    
    let ORDERS_STATUS_SUCCESS = 1
    let STATUS_CANCELLED      = 4
    let STATUS_ORDERED        = 3
    let STATUS_WAIT_APPROVAL  = 2
    let STATUS_ACTIVE         = 1
    let STATUS_INACTIVE       = 0
    
    var orders                = [Orders]()
    let loadingImg            = UIImage(named: "loading.gif")

    override func viewDidLoad() {
        super.viewDidLoad()
        FancyTools.authentication(self)
        loadOrders()
    }
    
    override func viewDidAppear(animated: Bool) {
        FancyTools.authentication(self)
        self.collectionView?.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return orders.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyOrdersCell", forIndexPath: indexPath) as MyOrdersCell
        
        // Configure the cell
        let order = orderAtIndexPath(indexPath)
        
        cell.name.text     = order.item.name
        cell.brand.text    = order.item.brand
        cell.fromUser.text = order.fromUser
        cell.price.text    = String(order.item.value)
        
        // use image if cached, else use loading image than fetch image in back
        if order.thumbnail != nil {
            cell.image.image = order.thumbnail
            
        } else {
            
            order.thumbnail  = loadingImg
            cell.image.image = loadingImg
            
//            Alamofire.
            request(.GET, order.imageURL(order.item.image))
                .response { (request, response, data, error) in
                    
                    // set and cache fetched image
                    let img = UIImage(data: data! as NSData)
                    order.thumbnail  = img
                    cell.image.image = img
            }
            
        }
        
        switch order.status {
            case STATUS_CANCELLED:
                cell.status.text      = "Annulé"
                cell.status.textColor = UIColor.redColor()
            case STATUS_ORDERED:
                cell.status.text      = "Commandé"
                cell.status.textColor = UIColor.blueColor()
            case STATUS_WAIT_APPROVAL:
                cell.status.text      = "En attente"
                cell.status.textColor = UIColor.orangeColor()
            case STATUS_ACTIVE:
                cell.status.text      = "Approuvé"
                cell.status.textColor = UIColor.greenColor()
            case STATUS_INACTIVE:
                cell.status.text      = "Refusé"
                cell.status.textColor = UIColor.redColor()
            default:
                cell.status.text = ""
        }

        return cell
    }

    @IBAction func home(sender: AnyObject) {
        var storyboard = UIStoryboard(name: "Main", bundle: nil)
        var controller = storyboard.instantiateViewControllerWithIdentifier("main") as UIViewController
        self.presentViewController(controller, animated: true, completion: nil)
    }
    
    func loadOrders() {
//        Alamofire.
            Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization":fancy_token]
//        Alamofire.
            request(.GET, "http://api.fancyswap.com/rest/1.0/orders")
                .responseJSON { (request, response, JSON_REPONSE, error) in
                
                let JSON_REPONSE: AnyObject = JSON_REPONSE!
                
                if let status = JSON_REPONSE["status"] as? Int {
                    if(status == self.ORDERS_STATUS_SUCCESS) {
                        self.orders.removeAll(keepCapacity: false)
                        
                        let ordersList = JSON_REPONSE["orders"] as NSArray
                        for anOrder in ordersList {
                            var order: Orders = Orders(dic: (anOrder as NSDictionary))
                            self.orders.append(order)
                        }
                        
                        self.collectionView?.reloadData()

                        
                    } else {
                        let message = JSON_REPONSE["message"] as? String
                        println("Erreur :\(message)")
                    }
                } else {
                    println("Erreur :\(JSON_REPONSE)")
                }
        }
    }
    
    func orderAtIndexPath(indexPath: NSIndexPath) -> Orders {
        return orders[indexPath.row]
    }
    
    func getOrderThumbImg(order: Orders) -> UIImage {
        
        var thumbImg: UIImage?
        
        // use image if cached, else use loading image than fetch image in back
        if order.thumbnail != nil {
            thumbImg = order.thumbnail
            
        } else {
            thumbImg = loadingImg
            
//            Alamofire.
            request(.GET, order.imageURL(order.item.image))
                .response { (request, response, data, error) in
                    
                    // set and cache fetched image
                    thumbImg = UIImage(data: data! as NSData)
            }
        }
        
        return thumbImg!
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "showOrderDetails" {
            let cell = sender as UICollectionViewCell
            let indexPath = collectionView?.indexPathForCell(cell)
            
            var order = orderAtIndexPath(indexPath!)
            
            let detailView   = segue.destinationViewController as MyOrderDetailsController
            detailView.order = order
        }
        
    }
    
}
